#include "drawform.h"
#include "ui_drawform.h"
#include <QKeyEvent>
#include <QMouseEvent>
#include <QPainter>
#include <QtMath>

DrawForm::DrawForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DrawForm)
{
    ui->setupUi(this);
}

DrawForm::~DrawForm()
{
    delete ui;
}

bool isFirst = true;
QPoint temppt;

void DrawForm::paintEvent(QPaintEvent *event) {
    painter = new QPainter(this);
    QPen pen;
      pen.setColor(Qt::red);
      pen.setWidth(3);
      painter->setPen(pen);

      for(auto i :MainList)
        i->Draw(painter);
}

void DrawForm::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_1)
    {    mDrawType = 1; ui->label->setText("开始画线");}
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_2)
    {    mDrawType = 2; ui->label->setText("开始画圆");}
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_3)
    {    mDrawType = 3; ui->label->setText("开始画矩形");}
    this->setCursor(Qt::CrossCursor);
}

void DrawForm::mousePressEvent(QMouseEvent *event)
{
    if(mDrawType == 1)
    {
        DwgLine *line = new DwgLine ;
        if(isFirst)
        {
            temppt =event->pos();
            isFirst = false;
        }
        else
        {
            DwgLine *line = new DwgLine;
            line->mStartPt = temppt;
            line->mEnd = event->pos();
            MainList.append(line);
            isFirst = true;
            update();
        }
    }
   if(mDrawType == 2)
   {
       DwgCircle *circle = new DwgCircle;
       if(isFirst)
       {
             temppt = event->pos();
             isFirst = false;
       }
       else
       {
             circle->mCenterPt = temppt;
             circle->mRad = qSqrt((temppt.x()-event->pos().x())*(temppt.x()-event->pos().x())+(temppt.y()-event->pos().y())*(temppt.y()-event->pos().y()));
             MainList.append(circle);
             isFirst = true;
             update();
        }
   }
   if(mDrawType == 3)
   {
       Dwgrectangle *rectangle = new Dwgrectangle ;
       if(isFirst)
       {
           temppt =event->pos();
           isFirst = false;
       }
       else
       {
           Dwgrectangle *rectangle = new Dwgrectangle;
           rectangle->mStartPt = temppt;
           rectangle->mEnd = event->pos();
           MainList.append(rectangle);
           isFirst = true;
           update();
       }
   }
}
